import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:search_people/bean/city.dart';
import 'package:search_people/bean/search/search_list.dart';
import 'package:search_people/utils/component/selection/model.dart';
import 'package:search_people/utils/httputils/http_man.dart';
import 'package:search_people/utils/httputils/net_api.dart';

import '../../../../utils/component/selection/state.dart';
import 'index.dart';

class SuperSearchController extends GetxController {
  SuperSearchController();

  final state = SuperSearchState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.rc = RefreshController();
  }

  void onRefresh() {
    state.pageIndex = 1;
    onRequestResults();
  }

  void onLoading() {
    state.pageIndex++;
    onRequestResults();
  }

  List<String> getNames(List<SectionIndex> idxs) {
    List<String> names = [];
    for (var e1 in idxs) {
      if (e1.idxs.isNotEmpty) {
        for (var e2 in e1.idxs) {
          names.add(e2.name);
        }
      } else {
        names.add(e1.name);
      }
    }
    return names;
  }

  List<String> getIds(List<SectionIndex> idxs) {
    List<String> names = [];
    for (var e1 in idxs) {
      if (e1.idxs.isNotEmpty) {
        for (var e2 in e1.idxs) {
          names.add(e2.val);
        }
      } else {
        names.add(e1.val);
      }
    }
    return names;
  }

  void onRequestResults() {
    if (state.conditions == null) {
      return;
    }
    var conditions = state.conditions;
    state.regionNames = getNames(conditions![0]!);
    state.schoolIds = getIds(conditions[1]!);
    var schoolNames = getNames(conditions[1]!);
    state.hometownNames = getNames(conditions[2]!);
    state.birthDateStrs = getNames(conditions[3]!);
    state.jobIds = getIds(conditions[4]!);
    var jobNames = getNames(conditions[4]!);

    state.words = [];
    state.words!.addAll(state.regionNames ?? []);
    state.words!.addAll(schoolNames);
    state.words!.addAll(state.hometownNames ?? []);
    var birthStrs = state.birthDateStrs?.map((e) => e.substring(0, 4));
    state.words!.addAll(birthStrs ?? []);
    state.words!.addAll(jobNames);

    postSuperSearch(
        birthDateStrs: state.birthDateStrs,
        hometownNames: state.hometownNames,
        jobIds: state.jobIds,
        regionNames: state.regionNames,
        schoolIds: state.schoolIds);
  }

  void actionSure(Map<int, List<SectionIndex>>? conditions) {
    state.conditions = conditions;
    state.isShowCondition = false;
    onRefresh();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() async {
    super.onReady();

    var sec0 = SelectionModel()
      ..title = '任职区域'
      ..isSelected = true
      ..canSearch = true
      ..searchPlaceholder = '选择区县'
      ..searchTap = () async {
        return await chooseCity();
      };

    loadCityData(sec0);

    var sec1 = SelectionModel()
      ..title = '毕业院校'
      ..showType = SelectionItemType.block
      ..levelCount = 2
      ..requestData = loadSchoolData
      ..searchPlaceholder = '搜索学校'
      ..canSearchInput = true
      ..canSearch = true;

    var sec2 = SelectionModel()
      ..title = '出生籍贯'
      ..canSearch = true
      ..searchPlaceholder = '选择区县'
      ..requestData = () {
        loadCityData(state.list[2]);
      }
      ..searchTap = () async {
        return await chooseCity();
      };

    var sec3 = SelectionModel()
      ..title = '出生年代'
      ..levelCount = 2
      ..showType = SelectionItemType.block
      ..requestData = loadBirthdayData;

    var sec4 = SelectionModel()
      ..title = '职务类别'
      ..requestData = loadJobData;

    state.list = [
      sec0,
      sec1,
      sec2,
      sec3,
      sec4,
    ];
    update();
  }

  void loadCityData(SelectionModel md) {
    Api.getCityList().then((res) {
      List cityData = res.data;
      List<CityModel> cityList =
          cityData.map((e) => CityModel.fromJson(e)).toList();
      List<SelectionModel> citys = cityList
          .map((e) => SelectionModel()
            ..title = e.name
            ..value = e.id
            ..children = e.citys
                    ?.map(
                      (e) => SelectionModel()
                        ..title = e.name
                        ..value = e.id,
                    )
                    .toList() ??
                [])
          .toList();
      md.children = citys;
      update();
    });
  }

  void loadSchoolData() {
    Api.getSchoolList().then((res) {
      List schoolData = res.data;

      List<SelectionModel> schools = schoolData
          .map((e) => SelectionModel()
            ..title = e['name'].toString()
            ..value = e['id'].toString())
          .toList();
      state.list[1].children = schools;
      update();
    });
  }

  void loadBirthdayData() {
    Api.getBirthdayList().then((res) {
      List schoolData = res.data;

      List<SelectionModel> schools = schoolData
          .map((e) => SelectionModel()
            ..title = e['name'].toString()
            ..value = e['id'].toString())
          .toList();
      state.list[3].children = schools;
      update();
    });
  }

  void loadJobData() {
    HomeApi.getJobs().then((res) {
      List jobData = res.data;
      List<SelectionModel> jobs = jobData
          .map((e) => SelectionModel()
            ..title = e['name'].toString()
            ..value = e['id'].toString()
            ..children = e['list']
                ?.map(
                  (e) => SelectionModel()
                    ..title = e['name'].toString()
                    ..value = e['id'].toString(),
                )
                .toList()
                .cast<SelectionModel>())
          .toList();
      state.list[4].children = jobs;
      update();
    });
  }

  Future<String> chooseCity() async {
    Result? result = await CityPickers.showCityPicker(
      context: Get.context!,
    );
    return '${result?.provinceName ?? ''}/${result?.cityName ?? ''}/${result?.areaName ?? ''}';
  }

  void postSuperSearch({
    List<String>? birthDateStrs,
    List<String>? hometownNames,
    List<String>? jobIds,
    List<String>? regionNames,
    List<String>? schoolIds,
  }) async {
    var res = await HomeApi.postSuperSearch(
      birthDateStrs: birthDateStrs ?? [],
      hometownNames: hometownNames ?? [],
      jobIds: jobIds ?? [],
      regionNames: regionNames ?? [],
      schoolIds: schoolIds ?? [],
      pageIndex: state.pageIndex,
    );
    List records = res.data['records'];
    if (state.rc.isRefresh) {
      state.rc.refreshCompleted();
    }
    if (state.rc.isLoading) {
      if (records.isEmpty) {
        state.rc.loadNoData();
      } else {
        state.rc.loadComplete();
      }
    }
    var results = records.map((e) => Records.fromJson(e)).toList();
    if (state.pageIndex == 0) {
      state.results = results;
    } else {
      state.results.addAll(results);
    }
    update();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.rc.dispose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
